//
//  NSTextFieldExtension.swift
//  JKTools
//
//  Created by 姜奎 on 2024/4/19.
//

import Cocoa

extension NSTextField {
    open override func performKeyEquivalent(with event: NSEvent) -> Bool {
        
        switch event.charactersIgnoringModifiers {
            case "a","A":
                return NSApp.sendAction(#selector(NSText.selectAll(_:)), to: self.window?.firstResponder, from: self)
            case "c","C":
                return NSApp.sendAction(#selector(NSText.copy(_:)), to: self.window?.firstResponder, from: self)
            case "v","V":
                return NSApp.sendAction(#selector(NSText.paste(_:)), to: self.window?.firstResponder, from: self)
            case "x","X":
                return NSApp.sendAction(#selector(NSText.cut(_:)), to: self.window?.firstResponder, from: self)
            default:
                return super.performKeyEquivalent(with: event)
        }
    }
}

extension NSTextField {

    private static var actionCloseAssociatedKey: Int = 0

    @objc func targetAction(with event: NSEvent) -> Bool {
        guard let actionClose = actionClose else { return false }
        return actionClose(self, event)
    }

    private var actionClose: ((NSTextField, NSEvent)-> Bool)? {
        get {
            return objc_getAssociatedObject(self, &Self.actionCloseAssociatedKey) as? ((NSTextField, NSEvent)->Bool)
        }
        set {
            objc_setAssociatedObject(self, &Self.actionCloseAssociatedKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }

    func addKeyDown(action:@escaping ((NSTextField, NSEvent)->Bool)) {
        self.actionClose = action
    }

    open override func keyDown(with event: NSEvent) {
        if targetAction(with: event) {
            return
        }
        super.keyDown(with: event)
    }
}
